package com.yonyou.pmclouds.basecom.util;

import com.yonyou.pmclouds.basecom.exception.BusinessException;

import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAUtil {
    public static String data="hello world";

    public static String publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDl1/Iu3DAV3Dhyv4POE+1FPs5l9w4ZP6XaRnnjEKb+S6C1NmH/a6rWfGSGK8l5QG0kYMRlcHxTTGh9hRKTFw9eK6iUlPtUVSQmSblLHweYVpVLvqzYoiHDAoTxf57H6O4L7I8b1DNnPkkp0gIp59tjEXW3c4p29cjXqPjGu4OS/wIDAQAB";

    private static String privateKey="MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBAOXX8i7cMBXcOHK/g84T7UU+zmX3Dhk/pdpGeeMQpv5LoLU2Yf9rqtZ8ZIYryXlAbSRgxGVwfFNMaH2FEpMXD14rqJSU+1RVJCZJuUsfB5hWlUu+rNiiIcMChPF/nsfo7gvsjxvUM2c+SSnSAinn22MRdbdzinb1yNeo+Ma7g5L/AgMBAAECgYEAzFuKq3t/DZC2Z+A8Mtio2C6VmTdmw7BBqKeM7AT8VZGsnDJ0Q4PZa8dCIcGA61wLLpMTTBYNlIqVRTUyZLHWKHcBFNv8t21M7LGuBmTyipTX9jKWFkQlOYquhMAho0c5plqzMjUxtr+559R4lvBFClzAOsl0cOWLI8BKN8ye/YECQQD8GEhsvtvDcEUBBecyUN2g4ESTj2PgxQJeYNxokclGwCnoPttew6bBGNVSq7i8bTYw+9qfV1HzH2h9InbDXL9hAkEA6WdsJRDq/3/fJWtHF154HARSv8IUYchzxpNggxcRGW2SEvZ96TyPmjVU5mLTOao2QM+EaO9zTwAZtKecW2lOXwJBAOVUpdYfjkZtxKhYmWkBfYzTWC8wm3inYC9BSGDsdsEhIT6AqAm+TN2O3Mk3JHhtlYXcJ5ca1ZcpdGGZz5aLsiECQQCLajVUpphX6R93EG80bD8+LO7oj5rxFXTiRiG968dQ8vvvy8BF0uDL8dM2kg0tQpiJeerTa0PrClpQaFWi3HHtAkEAkR6qL+7lwpwhq7+x+icF8nnZVWNjHQMkYq8zcs99blLOKHnNqvsk05O1vO9D++DOni9viraI7STbETlVTs4Jqw==";
    //非对称密钥生成方法，只能调用一次，生成一次保存到该class中的publicKey和privateKey
    private static KeyPair genKeyPair(int keyLength) throws Exception{
        KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        return keyPairGenerator.generateKeyPair();
    }

    public static void main(String[] args) throws Exception {

        KeyPair keyPair=genKeyPair(1024);

//        //获取公钥，并以base64格式打印出来
//        PublicKey publicKey=keyPair.getPublic();
//        System.out.println("公钥："+new String(DatatypeConverter.printBase64Binary((publicKey.getEncoded()))));
//
//        //获取私钥，并以base64格式打印出来
//        PrivateKey privateKey=keyPair.getPrivate();
//        System.out.println("私钥："+new String(DatatypeConverter.printBase64Binary((privateKey.getEncoded()))));
        //获取公钥
        PublicKey publicKey=getPublicKey(RSAUtil.publicKey);

        //获取私钥
        PrivateKey privateKey=getPrivateKey(RSAUtil.privateKey);

//        //公钥加密
//        byte[] encryptedBytes=encrypt(data.getBytes());
//        System.out.println("加密后："+new String(DatatypeConverter.printBase64Binary(encryptedBytes)));
//
//        //私钥解密
//        byte[] decryptedBytes=decrypt(encryptedBytes);
//        System.out.println("解密后："+new String(decryptedBytes));

        //公钥加密
        String encryptedBytes=encrypt(data);
        System.out.println("加密后："+encryptedBytes);

        //私钥解密
        String decryptedBytes=decrypt(encryptedBytes);
        System.out.println("解密后："+new String(decryptedBytes));

    }

    //将base64编码后的公钥字符串转成PublicKey实例
    public static PublicKey getPublicKey(String publicKey) throws Exception{
        byte[ ] keyBytes=DatatypeConverter.parseBase64Binary(publicKey);
        X509EncodedKeySpec keySpec=new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory=KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }

    //将base64编码后的私钥字符串转成PrivateKey实例
    public static PrivateKey getPrivateKey(String privateKey) throws Exception{
        byte[ ] keyBytes=DatatypeConverter.parseBase64Binary(privateKey);
        PKCS8EncodedKeySpec keySpec=new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory=KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }

    //公钥加密
    public static String encrypt(String content) throws Exception{
        Cipher cipher=Cipher.getInstance("RSA");//java默认"RSA"="RSA/ECB/PKCS1Padding"
        cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(RSAUtil.publicKey));
        return DatatypeConverter.printBase64Binary(cipher.doFinal(content.getBytes()));
    }

    //私钥解密
    public static String decrypt(String content) throws BusinessException{
        try
        {
            Cipher cipher=Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(RSAUtil.privateKey));
            byte[] by = DatatypeConverter.parseBase64Binary(content);
            return new String(cipher.doFinal(by));
        }
        catch(Exception e)
        {
            throw new BusinessException(e.getMessage(),e);
        }
    }

    //公钥加密
    public static byte[] encrypt(byte[] content) throws Exception{
        Cipher cipher=Cipher.getInstance("RSA");//java默认"RSA"="RSA/ECB/PKCS1Padding"
        cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(RSAUtil.publicKey));
        return cipher.doFinal(content);
    }

    //私钥解密
    public static byte[] decrypt(byte[] content) throws Exception{
        Cipher cipher=Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(RSAUtil.privateKey));
        return cipher.doFinal(content);
    }
}
